// miniprogram/pre_loadModules/settingModule/pages/userInfoSetting.js
import { urlPreFix } from '@/miniprogram/utils/httpReq'
import { updateMenberInfoReq, getMemberInfoReq } from '@/miniprogram/utils/API/user.js'
import { getstorage, removeStorage, setstorage, clearStorage } from '@/miniprogram/utils/storage.js'
import { getPhoneCode } from '@/miniprogram/utils/API/user.js'
import { reqUploadFile } from '@/miniprogram/pre_loadModules/settingModule/utils/file'
import { decode, encode, encodePublicKey } from '@/miniprogram/utils/security/security.js'
import { formatDate } from '@/miniprogram/utils/formatterTime.js'
import { userBehavior } from '@/miniprogram/utils/behaviors/userBehavior'



Page({
   behaviors: [userBehavior],
   data: {
      height: '0', propheight: '0',
      storeBindings: null,
      popupshow: false,
      showtitle: '',
      showIndex: null,
      updatebuff: {
         id: null,
         phone: null,
         nickName: null,
         header: null,
         sign: null,
         genders: null,
      },
      changedatabuff: [
         { id: 1, title: "用户昵称" },
         { id: 2, title: "签名设置" },
         { id: 3, title: "手机号更换" },
         { id: 4, title: "性别设置", menactive: '/static/icons/men.png', femaleactive: '/static/icons/female.png', menhidden: '/static/icons/menhidden.png', femalehidden: '/static/icons/femalehidden.png', },
         { id: 5, title: "生日设置" },
         { id: 6, title: "退出登录" }
      ],
      id: null,
      nickName: null,
      header: null,
      genders: null,
      birth: null,
      sign: null,
      status: null,
      urlBuff: null,
      isPhone: false,
      isCode: false,
      isgender: false,
      isheader: false,
      enableSendCode: false,
      enableSubmit: false,
      enableconfirm: false,
      timer: null,
      phone: null,
      code: null,
      timeDown: 60,
      startTimer: false,
      minDate: new Date(1900, 10, 1).getTime(),
      maxDate: new Date().getTime(),
      indicatorBirth: "yyyy-MM-dd",
      currentDate: [],
      saveAuthenation: false
   },
   onLoad(options) {
   },
   onShow() {
      let { userInfo, height, propheight, phone,header,genders ,nickName,birth } = this.data
      let temp = wx.getWindowInfo().windowHeight
      let s1 = userInfo.phone.substring(0, 3)
      let s2 = userInfo.phone.substring(7, 11)
      phone = s1 + "****" + s2
      height = temp + 'px'
      genders = userInfo.genders
      header = userInfo.header
      nickName = userInfo.nickName
      birth = userInfo.birth.toString()
      propheight = parseInt(temp / 2) + 50 + 'px'
      this.setData({
         height,
         propheight,
         phone,
         header,
         genders,
         birth,
         nickName
      })
   },
   bindchooseavatar(e) {
      let { updatebuff, isheader, userInfo, } = this.data
      var that = this;
      let urlBuff = e.detail.avatarUrl
      let name = "file"
      that.setData({
         urlBuff
      })
      wx.uploadFile({
         filePath: this.data.urlBuff,
         name: 'file',
         url: `${urlPreFix}file/upload`,
         header: { 'content-type': 'multipart/form-data' },
         success: (res) => {
            let buff = JSON.parse(res.data)
            updatebuff.header = buff.data
            updatebuff.id = userInfo.id,
               isheader = true
            that.setData({
               saveAuthenation: true,
               updatebuff,
               header : buff.data,
               isheader
            })
         },
      })
   },
   updatenickName(e) {
      let { changedatabuff, showIndex } = this.data
      let { detail } = e
      showIndex = changedatabuff[0].id,
         this.setData({
            popupshow: true,
            showIndex,
            showtitle: changedatabuff[0].title,
            idx: parseInt(e.currentTarget.dataset.idx)
         })
   },
   updatesign(e) {
      let { changedatabuff } = this.data
      let { detail } = e
      this.setData({
         popupshow: true,
         showIndex: changedatabuff[1].id,
         showtitle: changedatabuff[1].title,
      })
   },
   updategender(e) {
      let { changedatabuff } = this.data
      let { detail } = e
      this.setData({
         popupshow: true,
         showIndex: changedatabuff[3].id,
         showtitle: changedatabuff[3].title,
      })
   },
   updatebirthday(e) {
      let { changedatabuff } = this.data
      let { detail } = e
      this.setData({
         popupshow: true,
         showIndex: changedatabuff[4].id,
         showtitle: changedatabuff[4].title,
      })
   },
   updatephone(e) {
      let { changedatabuff } = this.data
      let { detail } = e
      this.setData({
         popupshow: true,
         showIndex: changedatabuff[2].id,
         showtitle: "手机号设置",
      })
   },
   getcodeBtn(e) {
      let { isPhone, enableSendCode, phone } = this.data
      let sendData = {}
      sendData.phone = phone
      if (enableSendCode && isPhone) {
         this.getcodeFunction(sendData)
         this.setData({
            startTimer: true
         })
         this.timerDown()
      }
   },
   phonebindblur(e) {
      let phone = e.detail.value
      let { notesMessage } = this.data
      let isPhone = /^1[3456789]\d{9}$/.test(phone)
      if (!phone) {
         wx.showToast({
            title: '请输入手机号！',
            icon: 'error'
         })
         return;
      } else if (!isPhone) {
         wx.showToast({
            title: '手机号格式不正确！',
            icon: 'error'
         })
         return
      } else {
         this.setData({
            isPhone: true,
            phone
         })
      }
   },
   codebindblur(e) {
      let code = e.detail.value
      let { notesMessage } = this.data
      if (!code) {
         wx.showToast({
            title: '请输入验证码！',
            icon: 'error'
         })
      } else {
         this.setData({
            isCode: true
         })
      }
   },
   onChangenickName(e) {
      let { nickName, id, userInfo, enableconfirm } = this.data
      nickName = e.detail
      id = userInfo.id
      if (nickName != null && nickName != '') {
         enableconfirm = true
      } else {
         enableconfirm = false
      }
      this.setData({
         nickName,
         id,
         enableconfirm: true
      })
   },
   onChangesign(e) {
      let { sign, id, userInfo, enableconfirm } = this.data
      sign = e.detail
      id = userInfo.id
      enableconfirm = true
      this.setData({
         sign, id, enableconfirm
      })
   },

   onChangephone(e) {
      let { phone, id, userInfo, isPhone, enableSendCode } = this.data
      phone = e.detail
      id = userInfo.id
      let isTrue = /^1[3456789]\d{9}$/.test(phone)
      if (isTrue) {
         enableSendCode = true,
            isPhone = true
      } else {
         enableSendCode = false,
            isPhone = false
      }
      this.setData({
         phone, id, enableSendCode, isPhone
      })
   },

   onChangeCode(e) {
      let { code, id, userInfo, isCode, isPhone, enableconfirm } = this.data
      code = e.detail
      id = userInfo.id
      isCode = code.length === 6 ? true : false
      if (isCode && isPhone) {
         enableconfirm = true
      } else {
         enableconfirm = false
      }
      this.setData({
         code, id, enableconfirm,
         isCode
      })
   },
   onChangegenders(e) {
      let { genders, isgender, enableconfirm } = this.data
      let { detail } = e
      console.log(detail);
      genders = parseInt(detail)
      isgender = true
      enableconfirm = true
      this.setData({
         genders,
         isgender,
         enableconfirm
      })
   },
   onchangeBirth(e) {
      let { currentDate, enableconfirm } = this.data
      let buff = formatDate(new Date(e.detail))
      currentDate = buff
      if (null != currentDate) {
         enableconfirm = true
      } else {
         enableconfirm = false
      }
      this.setData({
         currentDate,
         enableconfirm,
      })
   },
   confirmBtn(e) {
      let { userInfo, nickName, sign, phone, genders, birth, isPhone, isCode, saveAuthenation,
         showIndex, updatebuff, enableconfirm, popupshow, currentDate } = this.data
      switch (showIndex) {
         case 1:
            if (nickName === null || nickName === '') {
               return;
            }
            saveAuthenation = true
            updatebuff.nickName = nickName
            updatebuff.id = userInfo.id
            enableconfirm = false
            popupshow = false
            this.setData({
               updatebuff,
               updatebuff,
               enableconfirm,
               popupshow
            })
            break;
         case 2:
            if (sign === null || sign === '') {
               return;
            }
            updatebuff.sign = sign
            updatebuff.id = userInfo.id
            enableconfirm = false
            popupshow = false
            this.setData({
               updatebuff,
               updatebuff,
               enableconfirm,
               popupshow
            })
            break;
         case 3:
            if (!isPhone || !isCode) {
               return;
            }
            updatebuff.phone = phone
            updatebuff.id = userInfo.id
            enableconfirm = false
            popupshow = false
            this.setData({
               updatebuff,
               updatebuff,
               enableconfirm,
               popupshow,
            })
            break;
         case 4:
            if (genders === null || genders === '') {
               return;
            }
            updatebuff.genders = genders
            updatebuff.id = userInfo.id
            enableconfirm = false
            popupshow = false
            this.setData({
               updatebuff,
               updatebuff,
               enableconfirm,
               popupshow
            })
            break;
         case 5:
            birth = currentDate.toString()
            updatebuff.birth = birth
            if (birth === null || birth === '') {
               return;
            }

            updatebuff.id = userInfo.id
            enableconfirm = false
            popupshow = false
            this.setData({
               updatebuff,
               enableconfirm,
               birth,
               popupshow,
            })
            break;
      }
   },
   saveBtn() {
      let that = this
      let { updatebuff, saveAuthenation, isPhone, isCode, sign, genders, birth, isheader } = this.data
      if (!saveAuthenation && !isPhone && !isCode && !sign && !genders && !birth && !isheader) {
         wx.showToast({
            title: '没有修改任何参数',
            icon: 'error'
         })
         return;
      }
      wx.showModal({
         title: "确定提交保存吗？",
         success(res) {
            if (res.confirm) {
               that.memberUpdate(updatebuff)
            }
         }
      })
   },
   async memberUpdate(data) {
      let res = await updateMenberInfoReq(encodePublicKey(JSON.stringify(data)))
      if (res.data.code == 200) {
         let token = res.cookies
         removeStorage('uusd')
         token.forEach(item => {
            let s = {}
            s.key = item.split('=')[0];
            s.value = item.split('=')[1].replace("; Path", '')
            if (s.key === 'uusd') {
               setstorage(s.key, s.value)
            }
         }) 
         wx.showToast({
            title: '提交成功！',
         })
         this.updateUserInfo()
         wx.redirectTo({
            url: '/miniprogram/pre_loadModules/settingModule/pages/setting/setting',
         })
      }
   },
   async getMemberInfofun(data) {
      let res = await getMemberInfoReq(data)
      let { notesMessage } = this.data
      if (res.data.code == 200) {
         wx.showToast({
            title: '修改成功',
         })
         this.resetData()
         wx.showToast({
            title: notesMessage[2].success,
         })
      }
   },
   async getcodeFunction(data) {
      let res = await getPhoneCode(data)
      if (res.data.code == 200) {
         wx.showToast({
            title: '验证码已发送',
         })
      }
   },
   logout() {
      let { notesMessage, popupshow } = this.data
      popupshow = true
      this.setData({
         popupshow
      })
      if (askConfirm) {
         removeStorage("sessionToken")
         removeStorage("uusd")
         removeStorage("temp")
         this.setUserInfo(null)
         this.setToken(null)
         wx.showToast({
            title: '已退出登陆！',
         })
         wx.reLaunch({
            url: '/pages/index/index',
         })
      }
   },
   noteLogin() {
      wx.navigateTo({
         url: '/pages/profile/profile',
      })
   },
   login() {
      wx.navigateTo({
         url: '/pages/login/login',
      })
   },
   timerDown() {
      let timeDown = this.data.timeDown
      var that = this;
      that.setData({
         timer: setInterval(() => {
            timeDown--;
            that.setData({
               timeDown
            })
            if (timeDown <= 0) {
               clearInterval(that.data.timer)
               that.setData({
                  timeDown: 60,
                  startTimer: false
               })
            }
         }, 1000)
      })

   },
   onUnload() {
      this.setData({
         popupshow: false,
         enableconfirm: false,
         nickName: '',
         phone: '',
         code: '',
         sign: '',
         showtitle: '',
         showIndex: 0,
         enableSendCode: false
      })
   },
   cancelbtn() {
      this.setData({
         popupshow: false
      })
   },
   resetData() {
      this.setData({
         memberInfo: {},
         urlBuff: '',
         nickNamedialogShow: false,
         signdialogShow: false,
         phonedialogShow: false,
      })
   },

})